package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.controller.bean.Result;
import com.example.demo.dto.TaskRequestDTO;
import com.example.demo.mapper.TaskManageMapper;
import com.example.demo.mapper.entity.*;
import com.example.demo.service.TaskManageService;
import com.example.demo.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class TaskManageServiceImpl extends ServiceImpl<TaskManageMapper, Task> implements TaskManageService {
    @Autowired
    private TaskManageMapper mapper;


    @Override
    public PageVo<Task> getTaskList(PageBo pageBo) {
        List<Task> logs = mapper.selectList(new QueryWrapper<>());
        return new PageVo<>(pageBo, logs);
    }

    @Override
    public List<Task> searchTask(TaskRequestDTO request) {
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        if (request.getTaskName() != null) {
            queryWrapper.like("task_name", request.getTaskName());
        }
        if (request.getTaskType() != 0) {
            queryWrapper.eq("task_type", request.getTaskType());
        }
        if (request.getIsMainQuest() != 0) {
            queryWrapper.eq("is_main_quest", request.getIsMainQuest());
        }
        List<Task> result = mapper.selectList(queryWrapper);

        return result;
    }

    @Override
    public Result<String> addTask(TaskRequestDTO request) {
        Task newRequest = setTask(request);
       // Task newTask=mapper.addTask(newRequest);
        System.out.println("當前newRequest"+newRequest);
       if(mapper.insert(newRequest)>0){
           request.setTaskId(newRequest.getTaskId());
           List<StudentTask> newStudentTask = setStudentTask(request);

           if (mapper.batchInsertStudentTask(newStudentTask) > 0) {
               return Result.ok("添加成功");
           } else {
               return Result.fail("添加失败");
           }
       }
       return Result.fail("添加失败");

    }


    @Override
    public Result<String> deleteTask(Task task) {
        if(task!=null){
            if(mapper.deleteById(task)>0)
                return Result.ok("删除成功");
            else
                return Result.fail("删除失败");
        }
        return Result.fail("删除失败,选择内容为空");
    }

    @Override
    public void batchDeleteTask(List<Task> taskList) {
        mapper.batchDeleteTask(taskList);
    }

    @Override
    public int getTotalStudent() {
        return mapper.getTotalStudent();
    }

    @Override
    public int getTotalQuestions(int bankId) {
        return mapper.getTotalQuestions(bankId);
    }

    @Override
    public int getCollegeStudent(int collegeId) {
        return mapper.getTotalCollegeStudent(collegeId);
    }

    @Override
    public int getMajorStudent(int majorId) {
        return mapper.getTotalMajorStudent(majorId);
    }

    @Override
    public int getClassStudent(int clazz) {
        return mapper.getTotalClassStudent(clazz);
    }

    @Override
    public int getStudent(String studentNumber) {
        return mapper.getStudent(studentNumber);
    }


    private Task setTask(TaskRequestDTO request) {

        List<String> dateRange= request.getDateRange();
        if (dateRange != null && dateRange.size() == 2) {

            DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; // 用于解析输入的ISO 8601格式

            LocalDateTime startDate = LocalDateTime.parse(dateRange.get(0), inputFormatter);
            LocalDateTime endDate = LocalDateTime.parse(dateRange.get(1), inputFormatter);

            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            String formattedStartDate = startDate.format(outputFormatter);
            String formattedEndDate = endDate.format(outputFormatter);

            request.setStartTime(formattedStartDate);
            request.setEndTime(formattedEndDate);

            // 或者直接返回这两个字符串
            System.out.println("Start Date: " + formattedStartDate);
            System.out.println("End Date: " + formattedEndDate);
        } else {
            throw new IllegalArgumentException("Invalid date range. It should contain exactly two elements.");
        }

        return request;
    }

    private List<StudentTask> setStudentTask(TaskRequestDTO request) {
        List<StudentTask> studentTaskList = new ArrayList<>();
        List<Student> studentList = new ArrayList<>();
        //任务分配方式//1为按照学院分配//2为按照专业分配//3为按照班级分配//4为按照学生分配//5为随机分配
        if(request.getTaskAllocation()==1){ //按照学院分配
            studentList = mapper.selectStudentByCollege(request.getSelectedCollege());
        }
        if(request.getTaskAllocation()==2){ //按照专业分配
            studentList = mapper.selectStudentByMajor(request.getSelectedMajor());
        }
        if(request.getTaskAllocation()==3){ //按照班级分配
            studentList = mapper.selectStudentByClazz(request.getSelectedClazz());
        }
        if(request.getTaskAllocation()==4){ //按照学生分配
            studentList = mapper.selectStudentByNumber(request.getStudentNumber());
        }
        if(request.getTaskAllocation()==5){ //随机分配
            List<Student> selectedStudents = mapper.selectStudentList();
            Random random = new Random();
            Collections.shuffle(selectedStudents, random);
            studentList = selectedStudents.subList(0, request.getPeopleNumber());
        }
        for (Student student : studentList) {
            StudentTask studentTask = new StudentTask();
            studentTask.setTaskId(request.getTaskId());
            studentTask.setStudentId(student.getId());
            studentTask.setTaskAllocation(request.getTaskAllocation());
            studentTaskList.add(studentTask);
        }
        return studentTaskList;
    }
}
